/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package boundary;

import components.POwnerRegistration;
import components.POwnerUpdate;
import components.PPetRegistration;
import components.PVetRegistration;
import entity.Owner;
import entity.Pet;
import entity.Veterinarian;
import java.awt.event.MouseEvent;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

/**
 *
 * @author Juan
 */
public class MainWindow extends javax.swing.JFrame {

    /**
     * Creates new form MainWindow
     */
    public MainWindow() {
        initComponents();
        setLocationRelativeTo(null);
    }
    
    public void closeCurrentTab() {
        int selectedIndex = TPMainPane.getSelectedIndex();
        if (selectedIndex != -1) {
            TPMainPane.remove(selectedIndex);
        }
    }
    
    private void updateTreeItem(int nodeIndex, List objects) {
        //nodeIndex is the node where the objects should be inserted.
        DefaultTreeModel model = (DefaultTreeModel) TMainTree.getModel();
        DefaultMutableTreeNode updatedNode = (DefaultMutableTreeNode) model.getChild(model.getRoot(), nodeIndex);
        
        TreePath updateNodePath = new TreePath(model.getPathToRoot(updatedNode));
        boolean collapsed = TMainTree.isCollapsed(updateNodePath);
        updatedNode.removeAllChildren();
        model.reload();
        
        //Tree Set used to order the objects alphabetically.
        TreeSet<Owner> orderedObjects = new TreeSet<>(new Comparator() {

            @Override
            public int compare(Object o1, Object o2) {
                return o1.toString().compareToIgnoreCase(o2.toString());
            }
        });
        orderedObjects.addAll(objects);
        
        for (Object object : orderedObjects) {
            model.insertNodeInto(new DefaultMutableTreeNode(object), updatedNode, updatedNode.getChildCount());
        }
        
        if (!collapsed) {
            TMainTree.expandPath(updateNodePath);
        }
    }
    
    public void updatePets(List<Pet> pets) {
        updateTreeItem(0, pets);
    }
    
    public void updateOwners(List<Owner> owners) {
        updateTreeItem(1,owners);
    }
    
    public void updateVeterinarians(List<Veterinarian> veterinarians) {
        updateTreeItem(2, veterinarians);
    }
    
    private boolean showPopup(DefaultMutableTreeNode clickedNode, MouseEvent e) {
        DefaultTreeModel model = (DefaultTreeModel) TMainTree.getModel();
        TreePath treePath = new TreePath(model.getPathToRoot(clickedNode));
        TMainTree.expandPath(treePath);
        TMainTree.setSelectionPath(treePath);
        
        if (e.isPopupTrigger()) {
            switch (clickedNode.getUserObject().getClass().getSimpleName()) {
                case "Veterinarian":
                    MIEditEntity.setText("Edit veterinarian");
                    break;
                    
                case "Owner":
                    MIEditEntity.setText("Edit owner");
                    break;
                    
                case "Pet":
                    MIEditEntity.setText("Edit pet");
                    break;
                    
                case "String":
                    return false;
                    
                default:
            }
            PMTreePopupMenu.show(e.getComponent(), e.getX(), e.getY());
            return true;
        }
        
        return false;
    }
    
    private void editSelectedEntity() {
        TreePath selectionPath = TMainTree.getSelectionPath();
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) selectionPath.getLastPathComponent();
        Object userObject = selectedNode.getUserObject();
        
        if (userObject instanceof Owner) {
            TPMainPane.add("Update Owner", new POwnerUpdate((Owner) userObject));
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        PMTreePopupMenu = new javax.swing.JPopupMenu();
        MIViewEntity = new javax.swing.JMenuItem();
        MIEditEntity = new javax.swing.JMenuItem();
        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        TMainTree = new javax.swing.JTree();
        jScrollPane2 = new javax.swing.JScrollPane();
        TPMainPane = new javax.swing.JTabbedPane();
        jLabel1 = new javax.swing.JLabel();
        TFSearch = new javax.swing.JTextField();
        BSearch = new javax.swing.JButton();
        menuBar = new javax.swing.JMenuBar();
        MActionsMenu = new javax.swing.JMenu();
        MIRegisterOwner = new javax.swing.JMenuItem();
        MIRegisterPet = new javax.swing.JMenuItem();
        MIRegisterVet = new javax.swing.JMenuItem();
        MIExit = new javax.swing.JMenuItem();
        MEditMenu = new javax.swing.JMenu();
        MIEditSelected = new javax.swing.JMenuItem();
        MTabsMenu = new javax.swing.JMenu();
        MICloseCurrentTab = new javax.swing.JMenuItem();
        MHelpMenu = new javax.swing.JMenu();
        MIAbout = new javax.swing.JMenuItem();

        MIViewEntity.setText("View data");
        PMTreePopupMenu.add(MIViewEntity);

        MIEditEntity.setText("jMenuItem1");
        MIEditEntity.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MIEditEntityActionPerformed(evt);
            }
        });
        PMTreePopupMenu.add(MIEditEntity);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Healthy Pets Association System");
        setMinimumSize(new java.awt.Dimension(350, 500));

        jSplitPane1.setDividerLocation(200);

        javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("HPVA");
        javax.swing.tree.DefaultMutableTreeNode treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("Pets");
        treeNode1.add(treeNode2);
        treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("Owners");
        treeNode1.add(treeNode2);
        treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("Veterinarians");
        treeNode1.add(treeNode2);
        TMainTree.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        TMainTree.setToolTipText("Double click a name to see the details or right clic to view options.");
        TMainTree.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                TMainTreeMouseReleased(evt);
            }
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TMainTreeMouseClicked(evt);
            }
        });
        TMainTree.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                TMainTreeValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(TMainTree);

        jSplitPane1.setLeftComponent(jScrollPane1);

        jScrollPane2.setViewportView(TPMainPane);

        jSplitPane1.setRightComponent(jScrollPane2);

        jLabel1.setText("Search:");

        TFSearch.setText("Enter your search here...");
        TFSearch.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                TFSearchFocusGained(evt);
            }
        });

        BSearch.setText("Search");

        MActionsMenu.setMnemonic('a');
        MActionsMenu.setText("Actions");

        MIRegisterOwner.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        MIRegisterOwner.setMnemonic('o');
        MIRegisterOwner.setText("Register Owner");
        MIRegisterOwner.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MIRegisterOwnerActionPerformed(evt);
            }
        });
        MActionsMenu.add(MIRegisterOwner);

        MIRegisterPet.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.CTRL_MASK));
        MIRegisterPet.setMnemonic('s');
        MIRegisterPet.setText("Register Pet");
        MIRegisterPet.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MIRegisterPetActionPerformed(evt);
            }
        });
        MActionsMenu.add(MIRegisterPet);

        MIRegisterVet.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V, java.awt.event.InputEvent.CTRL_MASK));
        MIRegisterVet.setMnemonic('a');
        MIRegisterVet.setText("Register Veterinarian");
        MIRegisterVet.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MIRegisterVetActionPerformed(evt);
            }
        });
        MActionsMenu.add(MIRegisterVet);

        MIExit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
        MIExit.setMnemonic('x');
        MIExit.setText("Exit");
        MIExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MIExitActionPerformed(evt);
            }
        });
        MActionsMenu.add(MIExit);

        menuBar.add(MActionsMenu);

        MEditMenu.setMnemonic('e');
        MEditMenu.setText("Edit");

        MIEditSelected.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.CTRL_MASK));
        MIEditSelected.setText("Edit selected...");
        MIEditSelected.setEnabled(false);
        MIEditSelected.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MIEditSelectedActionPerformed(evt);
            }
        });
        MEditMenu.add(MIEditSelected);

        menuBar.add(MEditMenu);

        MTabsMenu.setMnemonic('t');
        MTabsMenu.setText("Tabs");

        MICloseCurrentTab.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        MICloseCurrentTab.setMnemonic('t');
        MICloseCurrentTab.setText("Close Current Tab");
        MICloseCurrentTab.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MICloseCurrentTabActionPerformed(evt);
            }
        });
        MTabsMenu.add(MICloseCurrentTab);

        menuBar.add(MTabsMenu);

        MHelpMenu.setMnemonic('h');
        MHelpMenu.setText("Help");

        MIAbout.setMnemonic('a');
        MIAbout.setText("About");
        MIAbout.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MIAboutActionPerformed(evt);
            }
        });
        MHelpMenu.add(MIAbout);

        menuBar.add(MHelpMenu);

        setJMenuBar(menuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(TFSearch, javax.swing.GroupLayout.DEFAULT_SIZE, 378, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(BSearch)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(TFSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(BSearch))
                .addGap(7, 7, 7)
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 438, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void MIExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MIExitActionPerformed
        System.exit(0);
    }//GEN-LAST:event_MIExitActionPerformed

    private void TMainTreeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TMainTreeMouseClicked
        TreePath pathForLocation = TMainTree.getPathForLocation(evt.getX(), evt.getY());
        if (pathForLocation != null) {
            DefaultMutableTreeNode clickedNode = (DefaultMutableTreeNode) pathForLocation.getLastPathComponent();
            if (!showPopup(clickedNode, evt)) {
                if (evt.getClickCount() == 2) {
                    if (clickedNode.getUserObject() instanceof String) {
                    } else {
                        System.out.println(clickedNode.getUserObject());
                    }
                }
            }
        }  
    }//GEN-LAST:event_TMainTreeMouseClicked

    private void MIRegisterOwnerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MIRegisterOwnerActionPerformed
        TPMainPane.add("Register Owner", new POwnerRegistration());
    }//GEN-LAST:event_MIRegisterOwnerActionPerformed

    private void MICloseCurrentTabActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MICloseCurrentTabActionPerformed
        closeCurrentTab();
    }//GEN-LAST:event_MICloseCurrentTabActionPerformed

    private void TFSearchFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_TFSearchFocusGained
        TFSearch.selectAll();
    }//GEN-LAST:event_TFSearchFocusGained

    private void MIRegisterVetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MIRegisterVetActionPerformed
        TPMainPane.add("Register Veterinarian", new PVetRegistration());
    }//GEN-LAST:event_MIRegisterVetActionPerformed

    private void MIRegisterPetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MIRegisterPetActionPerformed
        TPMainPane.add("Register Pet", new PPetRegistration());
    }//GEN-LAST:event_MIRegisterPetActionPerformed

    private void MIAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MIAboutActionPerformed
        // TODO
    }//GEN-LAST:event_MIAboutActionPerformed

    private void TMainTreeMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TMainTreeMouseReleased
        TreePath pathForLocation = TMainTree.getPathForLocation(evt.getX(), evt.getY());
        if (pathForLocation != null) {
            DefaultMutableTreeNode clickedNode = (DefaultMutableTreeNode) pathForLocation.getLastPathComponent();
            showPopup(clickedNode, evt);
        }
    }//GEN-LAST:event_TMainTreeMouseReleased

    private void MIEditEntityActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MIEditEntityActionPerformed
        editSelectedEntity();
    }//GEN-LAST:event_MIEditEntityActionPerformed

    private void TMainTreeValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_TMainTreeValueChanged
        TreePath path = evt.getPath();
        if (path != null) {
            DefaultMutableTreeNode lastNode = (DefaultMutableTreeNode) path.getLastPathComponent();
            if (lastNode.getUserObject() instanceof String) {
                MIEditSelected.setEnabled(false);
            } else {
                MIEditSelected.setEnabled(true);
            }
        } else {
            MIEditSelected.setEnabled(false);
        }
    }//GEN-LAST:event_TMainTreeValueChanged

    private void MIEditSelectedActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MIEditSelectedActionPerformed
        editSelectedEntity();
    }//GEN-LAST:event_MIEditSelectedActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new MainWindow().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BSearch;
    private javax.swing.JMenu MActionsMenu;
    private javax.swing.JMenu MEditMenu;
    private javax.swing.JMenu MHelpMenu;
    private javax.swing.JMenuItem MIAbout;
    private javax.swing.JMenuItem MICloseCurrentTab;
    private javax.swing.JMenuItem MIEditEntity;
    private javax.swing.JMenuItem MIEditSelected;
    private javax.swing.JMenuItem MIExit;
    private javax.swing.JMenuItem MIRegisterOwner;
    private javax.swing.JMenuItem MIRegisterPet;
    private javax.swing.JMenuItem MIRegisterVet;
    private javax.swing.JMenuItem MIViewEntity;
    private javax.swing.JMenu MTabsMenu;
    private javax.swing.JPopupMenu PMTreePopupMenu;
    private javax.swing.JTextField TFSearch;
    private javax.swing.JTree TMainTree;
    private javax.swing.JTabbedPane TPMainPane;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JMenuBar menuBar;
    // End of variables declaration//GEN-END:variables
}
